package com.wbao.dianniu.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.ImageView;

import com.alibaba.mobileim.YWChannel;
import com.alibaba.mobileim.channel.util.YWLog;
import com.alibaba.mobileim.login.YWLoginState;
import com.alibaba.sdk.android.util.NetworkUtils;
import com.arlen.photo.photopickup.util.DensityUtils;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.im.NotificationInitSampleHelper;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;


public class SplashActivity extends Activity  implements ILoginListener {
	private ImageView imageView;
	private LoginManager manager;
	boolean isFirstIn = false;
	public static final String AUTO_LOGIN_STATE_ACTION = "com.openim.autoLoginStateActionn";
	protected static final String TAG = LoginActivity.class.getSimpleName();
	private BroadcastReceiver mAutoLoginStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final int state = intent.getIntExtra("state", -1);
            YWLog.i(TAG, "mAutoLoginStateReceiver, loginState = " + state);
            if (state == -1){
                return;
            }
            handleAutoLoginState(state);
        }
    };
	
    private void init(String userId, String appKey) {
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
//        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();
    }
	
	private void handleAutoLoginState(int loginState){
        if (loginState == YWLoginState.logining.getValue()){
        }else if (loginState == YWLoginState.success.getValue()){
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            SplashActivity.this.startActivity(intent);
            SplashActivity.this.finish();
        } else {
        }
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		imageView = (ImageView) findViewById(R.id.splash_imageview);
		BitmapFactory.Options opts= new BitmapFactory.Options();
		opts. inJustDecodeBounds = true;
		int screenMax = Math.max(
				DensityUtils.getWindowWidth(this),
				DensityUtils.getWindowHeight(this));
		int imgMax = Math.max(opts.outWidth, opts.outHeight);
		int inSimpleSize = 1;
		if (screenMax <= imgMax) {
			inSimpleSize = Math.round(Math.max(screenMax, imgMax)
					/ Math.min(screenMax, imgMax));
		}
		opts.inSampleSize = inSimpleSize;
		System.out.println("inSimpleSize:" + inSimpleSize);
//		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.splash, opts);
		imageView.setBackgroundResource(R.drawable.splash);
		
		// 定时器
		Handler handler = new Handler();
		//获取自动登录状态
		SharedPreferencesUtils.init(this);
		boolean auto_status = SharedPreferencesUtils.getAutoLoginStatus();
		String username = SharedPreferencesUtils.getUserName();
		String password = SharedPreferencesUtils.getPassword();
		if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
			SharedPreferencesUtils.setAutoLoginStatus(false);
			auto_status = false;
		}
		// 判断网络是否可用，不可用，直接到登录界面
		boolean net  = NetworkUtils.isNetworkAvaiable(this);
		if(!net){
			auto_status = false;
			Notification.toast(this, "网络不可用，请检测网络");
		}
		
		if(auto_status){	//自动登录
			//获取用户名和密码 自动登录 
			manager = new LoginManager(this);
			manager.addLoginListener(this);
			manager.Login(this, username, password);
		}else{
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					startActivity(new Intent(SplashActivity.this,LoginActivity.class));
					finish();
				}
			}, 1 * 1000);
		}
	}
	
    @Override
    protected void onDestroy() {
        super.onDestroy();
        myUnregisterReceiver();
    }
	
	
	private void myRegisterReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(AUTO_LOGIN_STATE_ACTION);
        LocalBroadcastManager.getInstance(YWChannel.getApplication()).registerReceiver(mAutoLoginStateReceiver, filter);
    }
	
	private void myUnregisterReceiver(){
        LocalBroadcastManager.getInstance(YWChannel.getApplication()).unregisterReceiver(mAutoLoginStateReceiver);
    }
	
	@Override
	public void onFailure(int errorCode, String errorMsg) {
		// TODO Auto-generated method stub
		startActivity(new Intent(SplashActivity.this,LoginActivity.class));
		finish();
	}
	
	@Override
	public void onSuccess(LoginResponse objdata) {
		// TODO Auto-generated method stub
		Utils.saveLoginData(objdata);
		init(objdata.getEnvironmentName() + GlobalContext.accountId, getResources().getString(R.string.app_key));
		myRegisterReceiver();
		//初始化imik
//		LoginSampleHelper.getInstance().initIMKit(GlobalContext.mobile, getResources().getString(R.string.app_key));
		//登录成功时，登录IM
		loginIM(objdata.getEnvironmentName() + GlobalContext.accountId, SharedPreferencesUtils.getPassword());
	}

	public void loginIM(String userId,String password){
		// 成功 界面跳转
		startActivity(new Intent(SplashActivity.this, MainActivity.class));
		SplashActivity.this.finish();
	}
	@Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
	
	
}

